package com.woniu.fly.fairmall.wx.service;

import com.woniu.fly.fairmall.core.util.JacksonUtil;
import com.woniu.fly.fairmall.core.util.ResponseUtil;
import com.woniu.fly.fairmall.db.entity.QuestInfo;
import com.woniu.fly.fairmall.db.service.QuestInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户问卷数据
 */
@Component
 public class QuestUserService {

 	@Resource
 	private QuestInfoService questInfoService;

    public Object submit(Long userId, String body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Map map = JacksonUtil.parseObject(body, "param", Map.class);
        if (CollectionUtils.isEmpty(map)) {
            return ResponseUtil.badArgument();
        }
        Long questMainId = Long.parseLong(map.get("mainId").toString());
        List<Map<String, Object>> questList = (ArrayList) map.get("quest");
        QuestInfo questInfo;
        for (int i = 0; i < questList.size(); i++) {
            String answer = questList.get(i).get("answer").toString();
            Long questId = Long.parseLong(questList.get(i).get("questId").toString());
            if (StringUtils.isEmpty(answer)) {
                return ResponseUtil.fail(505, "您还未回答第"+(i+1)+"题");
            }
            questInfo = new QuestInfo();
            questInfo.setMainId(questMainId);
            questInfo.setUserId(userId);
            questInfo.setAddTime(LocalDateTime.now());
            questInfo.setAnswer(answer);
            questInfo.setDeleted(false);
            questInfo.setListId(questId);
            questInfoService.insert(questInfo);
        }
        return ResponseUtil.ok();
    }
}
